package com.yehebl.orm;

import com.yehebl.orm.check.DsCheckEntity;
import com.yehebl.orm.config.IConfig;
import com.yehebl.orm.data.connection.ConnectionManager;
import com.yehebl.orm.data.connection.LocalDataSource;
import com.yehebl.orm.data.connection.LocalJdbc;
import com.yehebl.orm.enums.DataType;
import com.yehebl.orm.util.LogUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 框架初始化sql
 */
public class DsInit {
	

	
	/**
	 * 初始化实体类
	 */
	public static void initEntity(IConfig config,String packageName,String url, String user, String password,String... tableName) {
		DsCheckEntity.start(config,packageName, url, user, password,tableName);
	}
	
	
	
	/**
	 * 运行初始化sql文件
	 * @param url mysql连接地址
	 * @param user  用户名
	 * @param password 密码
	 * @param file 初始化文件
	 */
	public static void initSql(IConfig config, String url, String user, String password, String file) {
		if (config.getDataType().equals(DataType.MYSQL)) {
			config.setJdbcNoInit(new LocalJdbc(
					new LocalDataSource(new ConnectionManager(url, "com.mysql.jdbc.Driver", user, password))));
		}
		initSql(config, file);
	}

	
	/**
	 * 运行初始化sql文件
	 * @param file sql文件
	 */
	public static void initSql(IConfig config, String file) {
		LogUtil.printInfo("正在执行初始化sql文件[" + file + "]");
		File f = new File(file);
		if (!f.exists()) {
			LogUtil.printWarn("执行初始化sql文件[" + file + "]出错");
			return;
		}
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8));
			String line;
			while ((line = reader.readLine()) != null) {
				if(line.startsWith("--")) {
					continue;
				}
				if(line.endsWith(";")) {
					sb.append(line).append("\r\n");
					continue;
				}
				sb.append(line);
			}
			reader.close();
		} catch (IOException e) {
			LogUtil.printWarn("执行初始化sql文件[" + file + "]出错:" + e.getMessage());
			throw new RuntimeException(e);
		}
		Connection connection = config.getJdbc().getConnection();
		try {
			connection.setAutoCommit(true);
			Statement st = connection.createStatement();
			String[] split = sb.toString().split("\r\n");
			for (String s : split) {
				LogUtil.printInfo("执行初始化sql文件中的sql[" + s + "]");
				st.execute(s);
			}
			st.close();
		} catch (SQLException e) {
			LogUtil.printWarn("执行初始化sql文件[" + file + "]出错:" + e.getMessage());
			throw new RuntimeException(e);
		}

	}
}
